import axios from "axios";
import baseUrl from './config'
import store from '@/store'
import {getToken} from '@/util/cookie'
import iView from 'iview'
import router from '@/router'

import constant from '@/util/Constant'

let {TOKEN_HEADER, TOKEN_PREFIX, LOGIN_PAGE_NAME} = constant
let instance = axios.create({
    baseURL: baseUrl,
    timeout: 5000,
});
instance.interceptors.request.use((config) => {
    config.headers[TOKEN_HEADER] = TOKEN_PREFIX + getToken();
    return config;
}, error => {
    iView.Message.error("服务器通信错误")
    return Promise.reject(error);
})
instance.interceptors.response.use((res) => {
    const {data} = res
    const {isSuccess, msg} = data.meta || {}
    if (!isSuccess && msg === "token不存在或者已经失效") {
        iView.Message.error(data.meta.msg)
        store.commit("logout")
        router.push(LOGIN_PAGE_NAME)
    }
    return data;
}, error => {
    iView.Message.error("服务器通信错误")
    return Promise.reject(error);
})
export default instance;
